<?php

namespace common\models\datas;

use common\components\bases\BaseModel;
use common\components\behaviors\UpdateCacheBehavior;
use common\components\extenders\MenuManage;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%brand}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $logo
 * @property string $url
 * @property string $description
 * @property string $keyword
 * @property integer $sort
 * @property integer $is_show
 * @property integer $created_at
 */
class Brand extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%brand}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['description'], 'string'],
            [['name'],'unique'],
            [['sort', 'is_show', 'created_at'], 'integer'],
            [['name', 'logo', 'url', 'keyword'], 'string', 'max' => 255]
        ];
    }

    /*将时间戳格式的时间按照date时间格式显示*/
    public function fields(){
        $fields = parent::fields();
        $fields['created_at'] = function(){
            return Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['updated_at'] = function(){
            return Yii::$app->formatter->asDatetime($this->updated_at);
        };
        return $fields;
    }

    public function extraFields()
    {
        return [
            'backend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
        ];
    }

    /**
     * @inheritdoc
     */
    
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '自动编号'),
            'name' => Yii::t('common', '品牌名称'),
            'logo' => Yii::t('common', '品牌logo'),
            'url' => Yii::t('common', '品牌官网'),
            'description' => Yii::t('common', '描述'),
            'keyword' => Yii::t('common', '关键词'),
            'sort' => Yii::t('common', '排序'),
            'is_show' => Yii::t('common', '是否显示'),
            'created_at' => Yii::t('common', '创建时间'),
        ];
    }

    /*自动添加创建更改时间*/
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'brand',
            ],
        ]);
    }


}
